/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-02-16
 * Time: 18:23
 */
public class Hash {
    public static class LinkNode {
        public int key;
        public int val;
        public LinkNode next;

        public LinkNode(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public LinkNode[] array;
    public int useSize;
    //初始长度为10
    public Hash() {
        this.array = new LinkNode[10];
    }
    //插入元素
    public void put(int key,int val){
        int index = key % array.length;
        if (array[index] == null){
            array[index] = new LinkNode(key,val);
        }
        LinkNode cur = array[index];
        LinkNode node = new LinkNode(key,val);
        while (cur != null){
            //key相同就用新的value将旧的value替换
            if (cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //头插法
        node.next = array[index];
        array[index] = node;
        useSize++;

        if (loadFactors() > 0.75){
            //扩大
            reSize();
        }
    }
    //计算负载因子
    public double loadFactors(){
        return useSize * 1.0 / array.length;
    }
    //
    public void reSize(){
        //将数组熔炉扩大为原来的两倍
        LinkNode[] tempArray = new LinkNode[array.length * 2];
        //将每个元素进行重新哈希
        for (LinkNode linkNode : array) {
            LinkNode cur = linkNode;
            while (cur != null) {
                LinkNode curNext = cur.next;
                int newIndex = cur.key % tempArray.length;
                cur.next = tempArray[newIndex];
                tempArray[newIndex] = cur;
                cur = curNext;
            }
        }
        array = tempArray;
    }
    //
    public int get(int key){
        int index = key % array.length;
        LinkNode cur = array[index];
        for (int i = 0; i < array.length; i++) {
            while (cur != null){
                if (cur.val == key){
                    return cur.val;
                }
                cur = cur.next;
            }
        }
        return -1;
    }
}
